<template>
  <div class="todo">
    <TodoAdd />

    <TodoList name="进行中" :todos="doingTodos" @bbb="onChange" />

    <TodoList name="已完成" :todos="doneTodos" @bbb="onChange" />

    <TodoFooter :todos="state.todos" />
  </div>
</template>

<script>
import TodoAdd from "@/components/TodoAdd.vue";
import TodoList from "@/components/TodoList.vue";
import TodoFooter from "@/components/TodoFooter.vue";
import { reactive, computed, provide } from "vue";

export default {
  components: {
    TodoAdd,
    TodoList,
    TodoFooter,
  },

  setup() {
    const state = reactive({
      todos: [
        { id: 1, name: "吃饭", status: "doing" },
        { id: 2, name: "睡觉", status: "doing" },
        { id: 3, name: "打豆豆", status: "done" },
        { id: 4, name: "洗脚", status: "done" },
      ],
    });

    const doingTodos = computed(() => {
      return state.todos.filter((item) => item.status === "doing");
    });

    const doneTodos = computed(() => {
      return state.todos.filter((item) => item.status === "done");
    });

    function onChange(payload) {
      console.log("App onChange", payload);
      // state.todos.xxx
      // state.todos.
      // 当前要操作的 todo 项目
      const curTodo = state.todos.find((todo) => todo.id === payload.id);
      console.log(curTodo);
      // 修改
      curTodo.status = payload.isChecked ? "done" : "doing";
    }

    // 提供商
    provide("abcd", (payload) => {
      console.log("App abcd", payload);
      state.todos = [];
    });

    // 更新某项 Todo内容
    provide("updateTodo", (payload) => {
      const index = state.todos.findIndex((todo) => todo.id === payload.id);
      state.todos.splice(index, 1, payload);
    });

    return {
      state,
      doingTodos,
      doneTodos,
      onChange,
    };
  },
};
</script>

<style scoped lang="scss">
.todo {
  margin: 50px auto;
  width: 750px;
  background-color: #ffffff;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
}
</style>
